package com.example.test.dialogfactory;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Xfermode;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author Liujin 2019/4/8:20:58:38
 */
public class PorterDuffView extends View {

    private Paint mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
    private Mode mMode;
    private Xfermode mXfermode;

    private Canvas mSrcCanvas;
    private Canvas mDstCanvas;

    private Bitmap mSrcBitmap;
    private Bitmap mDstBitmap;

    private RectF mRectF = new RectF();

    public PorterDuffView( Context context ) {

        this( context, null, 0 );
    }

    public PorterDuffView( Context context, AttributeSet attrs ) {

        this( context, attrs, 0 );
    }

    public PorterDuffView( Context context, AttributeSet attrs, int defStyleAttr ) {

        super( context, attrs, defStyleAttr );
        init();
    }

    private void init() {

        // 注意点 01 :关闭硬件加速
        setLayerType( View.LAYER_TYPE_SOFTWARE, null );
        mPaint.setStyle( Style.FILL );
    }

    @Override
    protected void onSizeChanged( int w, int h, int oldw, int oldh ) {

        super.onSizeChanged( w, h, oldw, oldh );

        mRectF.set( 0, 0, w, h );

        // 注意点 02 :使用bitmap,并且bitmap大小位置一致
        mSrcBitmap = Bitmap.createBitmap( w, h, Config.ARGB_8888 );
        mDstBitmap = Bitmap.createBitmap( w, h, Config.ARGB_8888 );
        mSrcCanvas = new Canvas( mSrcBitmap );
        mDstCanvas = new Canvas( mDstBitmap );

        mPaint.setColor( Color.BLUE );
        mSrcCanvas.drawRect( 120, 120, 320, 320, mPaint );
        mPaint.setColor( Color.RED );
        mDstCanvas.drawCircle( 100, 100, 80, mPaint );
    }

    public void setXfermode( Mode mode ) {

        mMode = mode;
        mXfermode = new PorterDuffXfermode( mode );
        invalidate();
    }

    @Override
    protected void onDraw( Canvas canvas ) {

        // 注意点 03 :saveLayer创建一个透明图层
        int layer = canvas.saveLayer( mRectF, mPaint, Canvas.ALL_SAVE_FLAG );

        // 注意点 04 :先绘制目标图层到背景图层,不要使用paint,不要使用paint,不要使用paint
        canvas.drawBitmap( mDstBitmap, 0, 0, null );
        // 注意点 05 :将原始图片叠加到目标图层,使用paint
        mPaint.setXfermode( mXfermode );
        canvas.drawBitmap( mSrcBitmap, 0, 0, mPaint );
        mPaint.setXfermode( null );

        canvas.restoreToCount( layer );
    }
}
